<template>
  <t-dialog
    v-model:visible="dialogVisible"
    :header="isEdit ? '编辑模型' : '新建模型'"
    width="600px"
    :confirm-btn="{ content: isEdit ? '更新' : '创建', theme: 'primary' }"
    :cancel-btn="{ content: '取消' }"
    @confirm="handleSubmit"
    @cancel="handleCancel"
  >
    <t-form
      ref="formRef"
      :data="formData"
      :rules="rules"
      label-width="100px"
      @submit="handleSubmit"
    >
      <t-form-item label="模型名称" name="name">
        <t-input
          v-model="formData.name"
          placeholder="请输入模型名称"
          :maxlength="100"
          clearable
        />
      </t-form-item>

      <t-form-item label="模型类型" name="type">
        <t-select
          v-model="formData.type"
          placeholder="请选择模型类型"
          :disabled="isEdit"
          @change="handleTypeChange"
        >
          <t-option value="KnowledgeQA" label="对话模型" />
          <t-option value="Embedding" label="嵌入模型" />
          <t-option value="Rerank" label="排序模型" />
        </t-select>
      </t-form-item>

      <t-form-item label="模型来源" name="source">
        <t-select
          v-model="formData.source"
          placeholder="请选择模型来源"
          :disabled="isEdit"
        >
          <t-option value="local" label="本地" />
          <t-option value="cloud" label="云端" />
        </t-select>
      </t-form-item>

      <t-form-item label="描述" name="description">
        <t-textarea
          v-model="formData.description"
          placeholder="请输入模型描述"
          :maxlength="500"
          :autosize="{ minRows: 3, maxRows: 5 }"
        />
      </t-form-item>

      <!-- 对话模型参数 -->
      <template v-if="formData.type === 'KnowledgeQA'">
        <t-divider>对话模型参数</t-divider>

        <t-form-item label="Base URL" name="parameters.base_url">
          <t-input
            v-model="formData.parameters.base_url"
            placeholder="请输入 Base URL（可选）"
            clearable
          />
        </t-form-item>

        <t-form-item label="API Key" name="parameters.api_key">
          <t-input
            v-model="formData.parameters.api_key"
            placeholder="请输入 API Key（可选）"
            type="password"
            clearable
          />
        </t-form-item>
      </template>

      <!-- 嵌入模型参数 -->
      <template v-if="formData.type === 'Embedding'">
        <t-divider>嵌入模型参数</t-divider>

        <t-form-item label="Base URL" name="parameters.base_url">
          <t-input
            v-model="formData.parameters.base_url"
            placeholder="请输入 Base URL（可选）"
            clearable
          />
        </t-form-item>

        <t-form-item label="API Key" name="parameters.api_key">
          <t-input
            v-model="formData.parameters.api_key"
            placeholder="请输入 API Key（可选）"
            type="password"
            clearable
          />
        </t-form-item>

        <t-form-item
          label="向量维度"
          name="parameters.embedding_parameters.dimension"
        >
          <t-input-number
            v-model="formData.parameters.embedding_parameters.dimension"
            placeholder="请输入向量维度"
            :min="1"
            :max="10000"
          />
        </t-form-item>

        <t-form-item
          label="截断令牌数"
          name="parameters.embedding_parameters.truncate_prompt_tokens"
        >
          <t-input-number
            v-model="
              formData.parameters.embedding_parameters.truncate_prompt_tokens
            "
            placeholder="请输入截断令牌数"
            :min="0"
            :max="100000"
          />
        </t-form-item>
      </template>

      <!-- 排序模型参数 -->
      <template v-if="formData.type === 'Rerank'">
        <t-divider>排序模型参数</t-divider>

        <t-form-item label="Base URL" name="parameters.base_url">
          <t-input
            v-model="formData.parameters.base_url"
            placeholder="请输入 Base URL（可选）"
            clearable
          />
        </t-form-item>

        <t-form-item label="API Key" name="parameters.api_key">
          <t-input
            v-model="formData.parameters.api_key"
            placeholder="请输入 API Key（可选）"
            type="password"
            clearable
          />
        </t-form-item>
      </template>

      <t-form-item label="设为默认" name="is_default">
        <t-switch v-model="formData.is_default" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from "vue";
import { MessagePlugin } from "tdesign-vue-next";
import type { FormInstance, FormRule } from "tdesign-vue-next";
import type {
  ModelItem,
  ModelType,
  CreateModelRequest,
  UpdateModelRequest,
} from "@/types/models";
import {
  getModelsList,
  getModelById,
  createModel,
  updateModel,
  deleteModel,
  setDefaultModel,
  testModelConnection,
} from "@/api/models";

// Props
interface Props {
  visible: boolean;
  modelData?: ModelItem | null;
  isEdit?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  modelData: null,
  isEdit: false,
});

// Emits
interface Emits {
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}

const emit = defineEmits<Emits>();

// 响应式数据
const formRef = ref<FormInstance>();
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit("update:visible", value),
});

// 表单数据
const formData = reactive<CreateModelRequest>({
  name: "",
  type: "KnowledgeQA",
  source: "local",
  description: "",
  parameters: {
    base_url: "",
    api_key: "",
    embedding_parameters: {
      dimension: 768,
      truncate_prompt_tokens: 0,
    },
  },
  is_default: false,
});

// 表单验证规则
const rules: Record<string, FormRule[]> = {
  name: [
    { required: true, message: "请输入模型名称", type: "error" },
    { min: 1, max: 100, message: "模型名称长度为1-100个字符", type: "error" },
  ],
  type: [{ required: true, message: "请选择模型类型", type: "error" }],
  source: [{ required: true, message: "请选择模型来源", type: "error" }],
  description: [
    { max: 500, message: "描述长度不能超过500个字符", type: "error" },
  ],
  "parameters.base_url": [
    { max: 500, message: "Base URL长度不能超过500个字符", type: "error" },
  ],
  "parameters.api_key": [
    { max: 500, message: "API Key长度不能超过500个字符", type: "error" },
  ],
  "parameters.embedding_parameters.dimension": [
    {
      type: "number",
      min: 1,
      max: 10000,
      message: "向量维度范围为1-10000",
      type: "error",
    },
  ],
  "parameters.embedding_parameters.truncate_prompt_tokens": [
    {
      type: "number",
      min: 0,
      max: 100000,
      message: "截断令牌数范围为0-100000",
      type: "error",
    },
  ],
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: "",
    type: "KnowledgeQA",
    source: "local",
    description: "",
    parameters: {
      base_url: "",
      api_key: "",
      embedding_parameters: {
        dimension: 768,
        truncate_prompt_tokens: 0,
      },
    },
    is_default: false,
  });
  formRef.value?.clearValidate();
};

// 监听模型数据变化
watch(
  () => props.modelData,
  (newData) => {
    if (newData && props.isEdit) {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        name: newData.name,
        type: newData.type,
        source: newData.source,
        description: newData.description,
        parameters: {
          base_url: newData.parameters.base_url || "",
          api_key: newData.parameters.api_key || "",
          embedding_parameters: newData.parameters.embedding_parameters || {
            dimension: 768,
            truncate_prompt_tokens: 0,
          },
        },
        is_default: newData.is_default,
      });
    } else {
      // 新建模式，重置表单
      resetForm();
    }
  },
  { immediate: true }
);

// 监听对话框显示状态
watch(
  () => props.visible,
  (visible) => {
    if (visible && !props.isEdit) {
      resetForm();
    }
  }
);

// 处理类型变化
const handleTypeChange = (value: ModelType) => {
  // 重置参数
  formData.parameters = {
    base_url: "",
    api_key: "",
    embedding_parameters: {
      dimension: 768,
      truncate_prompt_tokens: 0,
    },
  };
};

// 处理提交
const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate();
    if (!valid) return;

    let response;
    if (props.isEdit && props.modelData) {
      // 更新模型
      const updateData: UpdateModelRequest = {
        name: formData.name,
        description: formData.description,
        parameters: formData.parameters,
        is_default: formData.is_default,
      };
      response = await updateModel(props.modelData.id, updateData);
    } else {
      // 创建模型
      response = await createModel(formData);
    }

    if (response.success) {
      MessagePlugin.success(props.isEdit ? "更新成功" : "创建成功");
      emit("success");
    } else {
      MessagePlugin.error(
        response.message || (props.isEdit ? "更新失败" : "创建失败")
      );
    }
  } catch (error) {
    console.error("提交失败:", error);
    MessagePlugin.error(props.isEdit ? "更新失败" : "创建失败");
  }
};

// 处理取消
const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style lang="less" scoped>
// 表单样式可以根据需要添加
</style>
